// const baseUrl = "http://api.crqcn.com/";
const baseUrl = "http://localhost:3000/";

function fun(url, method, data, header) {
  data = data || {};
  header = header || {};
  wx.showNavigationBarLoading();
  if (url.toLowerCase().indexOf('http://') !== 0 && url.toLowerCase().indexOf('https://') !== 0) {
    url = url.replace(/^\//, "");
    url = baseUrl + url;
  }
  if (wx.getStorageSync("accessToken")) {
    header["Access-Token"] = wx.getStorageSync("accessToken");
    header["Permit-Token"] = wx.getStorageSync("permitToken");
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      header: header,
      data: data,
      method: method,
      success: (response) => {
        if ('access-token' in response.header) {
          wx.setStorage({
            key: "accessToken",
            data: response.header["access-token"]
          });
        }
        if (typeof response.data === 'object') {
          if ('flag' in response.data) {
            if ('code' in response.data) {
              response.data.code = parseInt(response.data.code);
              if (response.data.flag === 'False') {
                if (response.data.code === 0) {
                  wx.showToast({
                    title: response.data.message,
                    icon: 'none'
                  });
                  return reject();
                } else if (response.data.code === 1) {
                  wx.showToast({
                    title: "登陆超时，请重新登陆",
                    icon: 'none'
                  });
                  return reject();
                } else if (response.data.code === 2) {
                  wx.showToast({
                    title: "您暂无权限执行该操作",
                    icon: 'none'
                  });
                  return reject();
                }
              }
            }
          }
        }
        return resolve(response);
      },
      fail: reject,
      complete: () => {
        wx.hideNavigationBarLoading();
      }
    });
  });
}

wx.$http = {
  baseUrl: baseUrl,

  "get": function(url, data, header) {
    return fun(url, "GET", data, header);
  },

  "post": function(url, data, header) {
    return fun(url, "POST", data, header);
  }
};